/*
 posts api 路由
 */

var _ = require('lodash');

var models = require('../models/index');
var PostsModel = models.Posts;
var UserModel = models.User;

var PostsProxy = require('../proxy/posts');
var UserProxy = require('../proxy/users');
var config = require('../config');
var EventProxy = require('eventproxy');

var index = function(req,res,next){
    var page = parseInt(req.query.page,10) || 1;
    page= page > 0 ? page : 1;
    var limit = Number(req.query.limit) || config.list_posts_count;
    var options = {skip:(page-1)*limit,limit:limit,sort:'_id'};
    var ep = new EventProxy();
    ep.fail(next)

    PostsModel.find({},'',options,ep.done('posts'));

    ep.all('posts',function(posts){
        posts.forEach(function(post){
            UserModel.findById(post.uid,ep.done(function(user){
                post.author = user;
                ep.emit('user');
            }))
        })
        ep.after('user',posts.length,function(){
            posts = posts.map(function(post){
                return _.pick(post,['id','uid','author']);
            })
            res.send({data:posts});
        })
    })
}

exports.index = index;

var create = function(req,res,next){
    var uid = req.body.uid;
    var contentText = req.body.contentText;

    PostsProxy.newAndSave(uid,contentText,function(err,post){
        if(err){
            return next(err);
        }
        res.send({success:true,
                post_id:post.id
        })
    })

}

exports.create = create;
